/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.chain;

import java.util.List;
import tal.drivechain.chain.script.ScriptCommand;
import tal.drivechain.parsing.ModuleCommandParser;
import tal.drivechain.parsing.Tokenizer;
import tal.drivechain.plugin.Module;
import tal.drivechain.system.PluginLoader;

/**
 *
 * @author Main
 */
public abstract class Patcher {
    public abstract void configure(List<ScriptCommand> configuration) throws IllegalArgumentException;
    public abstract void patchNodes(Chain chain) throws IllegalArgumentException, AbortChainException;
    public abstract void executePatchCommand(Chain chain, ScriptCommand command) throws IllegalArgumentException, AbortChainException;
    public abstract boolean isPatcherCommand(ScriptCommand command);

    protected ChainNode getNode(String name, Chain chain) throws IllegalArgumentException, AbortChainException {
        if (name.startsWith("{")) { //anonymous node
            // TODO fix so it can patch between chains and any other kind of node.

            if (Tokenizer.balanced(name, 0, '{', '}')!=-1) {
                String strModule = name.substring(1, name.length()-1);
                ModuleCommandParser parser = new ModuleCommandParser(strModule);
                Module module = PluginLoader.getModule(parser.getModuleName());
                chain.addChild(module);
                module.parseProperties(parser.getModuleProperties());
                module.setupProperties();
                module.getParentChain().dispatchNodeConfigured(module);
                return module;
            } else throw new IllegalArgumentException("Missing closing bracket (}) for anonymous node.");
        } else {
            ChainNode node = chain.getChild(name);
            if (node==null)
                throw new IllegalArgumentException("Can't find node " + name + " in the chain " + chain.getPath());
            else return node;
        }
    }
}
